package com.hao.wms.service.impl;

import com.hao.wms.dao.IPermissionDao;
import com.hao.wms.domain.Permission;
import com.hao.wms.mvc.BaseAction;
import com.hao.wms.query.PageResult;
import com.hao.wms.query.QueryObject;
import com.hao.wms.service.IPermissionService;
import com.hao.wms.util.PermissionUtil;
import com.hao.wms.util.RequiredPermission;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class PermissionServiceImpl implements IPermissionService, ApplicationContextAware {
	private ApplicationContext ctx;
	private IPermissionDao dao;

	public void setDao(IPermissionDao dao) {
		this.dao = dao;
	}

	@Override
	public void delete(Permission e) {
		dao.delete(e);

	}

	@Override
	public List<Permission> list() {
		return dao.list();
	}

	@Override
	public PageResult query(QueryObject qo) {
		return dao.query(qo);
	}

	@Override
	public void reload() {
		// 得到容器中所有action
		Map<String, BaseAction> actions = ctx.getBeansOfType(BaseAction.class);
		Set<String> expressions = new HashSet<>();
		List<Permission> list = list();
		for (Permission permission : list) {
			expressions.add(permission.getExpression());
		}
		for (Entry<String, BaseAction> entry : actions.entrySet()) {
			Class<?> actionClass = entry.getValue().getClass();
			Method[] ms = actionClass.getDeclaredMethods();
			for (Method method : ms) {
				String expression = PermissionUtil.createExpression(method);
				if (!expressions.contains(expression)) {
					if (method.isAnnotationPresent(RequiredPermission.class)) {
						RequiredPermission rp = method.getAnnotation(RequiredPermission.class);
						Permission permission = new Permission();
						permission.setName(rp.value());
						permission.setExpression(expression);
						dao.save(permission);
					}
				}
			}
		}

	}

	@Override
	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		this.ctx = ctx;

	}

}
